package com.dctobacco.dongchengtobaccoandroid.fragment;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import java.util.ArrayList;
import java.util.List;


public class MyFragmentController {
    private int containerId;
    private FragmentManager fragmentManager;
    private static MyFragmentController controller;
    private List<Fragment> fragments;


    public MyFragmentController(FragmentActivity activity, int containerId, List<Fragment> fragmentList){
        this.containerId = containerId;
        fragmentManager = activity.getSupportFragmentManager();
        initFragment(fragmentList);
    }


    public void initFragment(List<Fragment> fragmentList){
        fragments = new ArrayList<Fragment>();
        for(Fragment fragment:fragmentList){
            fragments.add(fragment);
        }

        FragmentTransaction ft = fragmentManager.beginTransaction();
        for(Fragment fragment:fragments){
            ft.add(containerId, fragment);
        }
        ft.commit();
    }

    public int showFragment(int position){
        hideFragment();
        FragmentTransaction ft = fragmentManager.beginTransaction();
        Fragment fragment = fragments.get(position);
        ft.show(fragment);
        ft.commitAllowingStateLoss();
        return position;
    }

    public void hideFragment(){
        FragmentTransaction ft = fragmentManager.beginTransaction();
        for(Fragment fragment:fragments){
            ft.hide(fragment);
        }
        ft.commitAllowingStateLoss();
    }

    public Fragment getFragment(int position){
        return fragments.get(position);
    }
}
